package com.weishenai.customerassistant.controller.weChat;

import com.weishenai.customerassistant.common.Result;
import com.weishenai.customerassistant.entity.FactFinder;
import com.weishenai.customerassistant.service.FactFinderService;
import com.weishenai.customerassistant.service.SubstationService;
import com.weishenai.customerassistant.utils.DateUtil;
import com.weishenai.customerassistant.utils.WeChatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = "小程序_检察员信息")
@RestController
@RequestMapping("/wechat/fact")
public class FactFinderWechatController {
    @Autowired
    private FactFinderService factFinderService;

    @Autowired
    private WeChatUtil weChatUtil;

    @ApiOperation("小程序_根据微信的临时code登录，如果失败则需要代表第一次登录，需要完善信息")
    @ApiImplicitParam(name = "code", value = "登录微信的临时code")
    @PostMapping("/login/{code}")
    public Object login(@PathVariable("code") String code) {
        String openId = weChatUtil.getOpenId(code);
        if (openId == null) return Result.failed("code错误或者失效");
        FactFinder login = factFinderService.login(openId);
        return login != null ? Result.success(login) : Result.failed("该用户没有注册");
    }

    @ApiOperation("小程序_创建一个新的检察员")
    @PostMapping("/create/{factName}/{substationName}/{code}")
    public Object create(@PathVariable("factName") String factName, @PathVariable("substationName") String substationName, @PathVariable("code") String code) {
        if (substationName == null) return Result.failed("请选择供电站");
        if (factName == null) return Result.failed("请输入勘察院名字");
        FactFinder factFinder = new FactFinder();
        factFinder.setFactName(factName);
        factFinder.setCreatedTime(DateUtil.getTime());
        factFinder.setState(true);
        factFinder.setSubstationName(substationName);
        String openId = weChatUtil.getOpenId(code);
        log.info("code：" + code);
        log.info("获取到的openID: " + openId);
        if (openId == null || openId.equals("")) return Result.failed("code错误、失效或者已经使用过！");
        factFinder.setWeixinId(openId);
        Integer result = factFinderService.createFactFinder(factFinder);
        return result > 0 ? Result.success() : Result.failed("该用户已注册");
    }
}
